//
//  AppDelegate.swift
//  WeiBoSwift
//
//  Created by rong on 15/6/24.
//  Copyright © 2015年 rong. All rights reserved.
//

import UIKit

//全局变量记录用户信息
var sharedUserAccount = UserAccount.loadAccount()

let SwitchRootVCNotication = "SwitchRootVCNotication"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.rootViewController = defaultViewController() //MainViewController() //WelcomeViewController()//NewFeatureViewController() //
        window?.makeKeyAndVisible()
        
        //底部的颜色渲染
        UITabBar.appearance().tintColor = UIColor.orangeColor()
        //顶部导航栏的颜色渲染
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        
        //

       //print("程序刚启动，解档数据: \(UserAccount.loadAccount())")
        
        //注册通知,  如果写switchViewController会出错，少了一个 ：
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: SwitchRootVCNotication, object: nil)
        
        return true
    }
    
    //接收到通知的切换控制器
    func switchViewController(param: NSNotification){
        
        //判断object是否为 true， 如果是， 显示MainViewController
        let isMainVC = param.object as! Bool
        
        window?.rootViewController = isMainVC ? MainViewController() : WelcomeViewController()
        
    }

   //判断加载的默认的控制器
    private func defaultViewController() -> UIViewController{
    
        //用户是否登录
        if sharedUserAccount != nil {
        
            //如果登录，看是否有新版本, “如果是新版本，NewFeatureViewController”     “不是新版本，WelcomeViewController”
            return  isNewVersion() ? NewFeatureViewController() : WelcomeViewController()
        }
        
        return MainViewController()
    }
    
    private func isNewVersion() -> Bool
    {
        //1.获取应用程序的当前版本
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        
        //swift 1.2中需要使用这个
        //let version = NSNumberFormatter().numberFromString(currentVersion)!.doubleValue
        //swift 2.0中使用下面的
        let version = Double(currentVersion)
        print(version)
        
        //2.获取应用程序之前的版本，从用户偏好中读取
        let versionKey = "versionKey"
        let sandBoxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(versionKey)
        print(sandBoxVersion)
        
        //3.将当前版本写入 用户偏好
        NSUserDefaults.standardUserDefaults().setDouble(version!, forKey: versionKey)
        //从xcode6.0开始就不需要 同步了
        //NSUserDefaults.standardUserDefaults().synchronize()
        
        return version > sandBoxVersion
    }

}

